<script setup lang="ts">
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import { getSalesDetailList , updateSalesDetail } from "@/api/sales/sales-list.ts";
import type { SalesDetail } from "@/api/sales/sales-list.ts";
import SalesDetailAdd from "./sales-add.vue";

const salesTypeMap = {
  1: '正常销售',
  2: '全额顶销',
  3: '部分顶销',
}
const salesStatusMap = {
  1: '暂存',
  2: '已保存',
  3: '作废',
}
const paymentStatusMap = {
  1: '未回款',
  2: '部分回款',
  3: '全部回款',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '销售编号',
    dataIndex: 'salesId',
  },
  {
    title: '销售日期',
    dataIndex: 'salesDate',
  },
  {
    title: '销售省份',
    dataIndex: 'provincesCode',
  },
  {
    title: '销售城市',
    dataIndex: 'citiesCode',
  },
  {
    title: '客户名称',
    dataIndex: 'customerId',
  },
  {
    title: '销售类型',
    dataIndex: 'salesType',
  },
  {
    title: '自动总金额',
    dataIndex: 'salesTotalPrice',
  },
  {
    title: '实际销售总金额',
    dataIndex: 'salesActualTotalPrice',
  },
  {
    title: '抵消采购项金额',
    dataIndex: 'salesOffsetAmount',
  },
  {
    title: '订单状态',
    dataIndex: 'salesStatus',
  },
  {
    title: '销售人',
    dataIndex: 'salesPerson',
  },
  {
    title: '回款状态',
    dataIndex: 'salesPaymentStatus',
  },
  {
    title: '备注',
    dataIndex: 'salesRemarks',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])
const loading = shallowRef(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 100,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总订单数：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
// 订单数据集
const dataSource = shallowRef<SalesDetail[]>([])
// 搜索条件
const formModel = reactive<SalesDetail>({
  salesDate: undefined,
  customerId: undefined,
  salesType: undefined,
  salesStatus: undefined,
  salesPaymentStatus: undefined,
})

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getSalesDetailList({
      ...formModel,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    })
    console.log("加载销售订单数据完成")
    console.log(data)
    dataSource.value = data.list ?? []
    pagination.total=data.count
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.salesDate = undefined
  formModel.customerId = undefined
  formModel.salesType = undefined
  formModel.salesStatus = undefined
  formModel.salesPaymentStatus = undefined
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: SalesDetail) {
  const close = message.loading('删除中......')
  try {
    const res = await updateSalesDetail(record)
    if (res.code === 200)
      await init()
    message.success('删除成功')
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

function handleCheckAllChange(e: any) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

const salesDetailAdd = ref<InstanceType<typeof SalesDetailAdd>>()

async function handleAdd(){
  console.log("进入添加销售记录")
  salesDetailAdd.value?.open()
}

async function handleEdit(record){
  //TODO 待补充仓库类型编号
  salesDetailAdd.value?.open(record)
}

/**
 * checkbox点击事件
 *
 */
function handleCheckChange(value: any) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="4">
            <a-form-item name="name" label="销售日期">
              <a-date-picker  v-model:value="formModel.salesDate" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="desc" label="所属客户">
              <a-input v-model:value="formModel.customerId" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="salesType" label="销售类型">
              <a-select
                  v-model:value="formModel.salesType"
              >
                <a-select-option value="1">
                  正常销售
                </a-select-option>
                <a-select-option value="2">
                  全额顶销
                </a-select-option>
                <a-select-option value="3">
                  部分顶销
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="salesStatus" label="订单状态">
              <a-select
                  v-model:value="formModel.salesStatus"
              >
                <a-select-option value="1">
                  暂存
                </a-select-option>
                <a-select-option value="2">
                  已保存
                </a-select-option>
                <a-select-option value="3">
                  作废
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="salesStatus" label="回款状态">
              <a-select
                  v-model:value="formModel.salesPaymentStatus"
              >
                <a-select-option value="1">
                  未回款
                </a-select-option>
                <a-select-option value="2">
                  部分回款
                </a-select-option>
                <a-select-option value="3">
                  全部回款
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="销售记录">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加销售记录
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="handleDelete(scope?.record as SalesDetail)">
                作废
              </a>
              <a @click="handleDelete(scope?.record as SalesDetail)">
                查看详情
              </a>
              <a v-if="scope?.record?.salesStatus===0" @click="handleDelete(scope?.record as SalesDetail)">
                删除
              </a>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesType'">
            <div gap-2>
              {{ salesTypeMap[scope?.record?.salesType as keyof typeof salesTypeMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesStatus'">
            <div gap-2>
              {{ salesStatusMap[scope?.record?.salesStatus as keyof typeof salesStatusMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesPaymentStatus'">
            <div gap-2>
              {{ paymentStatusMap[scope?.record?.salesPaymentStatus as keyof typeof paymentStatusMap] as string }}
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
  </page-container>
</template>
